package cn.edu.whu.forecast.schudule.crawl;

import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DownloadPicFromUrl {
    public static void main(String[] args) {
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String url = "https://pi.weather.com.cn/i/product/pic/l/sevp_aoc_rdcp_sldas_ebref_az9591_l88_pi_"+time+".png";
        String path="C:\\Users\\Administrator\\Desktop\\Z_RADA_I_Z9591_"+time+"_P_DOR_RDCP_CR.PNG";
        downloadPicture(url,path);
    }
    //链接url下载图片
    private static void downloadPicture(String urlList,String path) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(buffer);//返回Base64编码过的字节数组字符串
            System.out.println(encode);
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
